<template>
	<scroll-view id="m_tab" :scroll-x="true" :scroll-with-animation="true"
		:scroll-left="tabConfig.scrollLeft">
		<view class="m_tab_container" v-if="config">
			<view class="m_tab_item" v-for="(i,idx) in config.array" :key="idx" :id="'m-tab-'+idx"
				@tap.stop="OnActiveDraw($event,i,idx)">
				<view class="circle_item">
					<!-- <image class="circle_img" src="../../static/logo.png"></image> -->
					<text>{{i.key}}</text>
				</view>
			</view>
		</view>
	</scroll-view>
</template>

<script>
	export default {
		props:{
			config:{
				type:Object,
				required:true,
				default:{
					array:[{
						key:"全部"
					}],
				}
			}
		},
		data() {
			return {
				tabConfig: {
					width: 0,
					active: 0,
					elWidth: 0,
					scrollLeft: 0,
					left: 0,
					arrowWidth: 0,
				}
			}
		},
		mounted() {
            this.GetConfig();
		},
		watch:{
			// config:{
			// 	handler:(nval,oval)=>{
			// 		console.log(nval,oval)
			// 		if(nval.array&&nval.array.length>0){
			// 			this.GetConfig();
			// 		}
			// 	},
			// 	deep:true,
			// }
		},
		methods: {
			GetConfig() {
				//初始化求出滚动的宽度
				uni.createSelectorQuery().in(this).select('#m_tab').boundingClientRect((rect) => {
					console.log(rect)
					this.tabConfig.width = Math.round(rect.width);
				}).exec();
				
				
				
			},
			OnActiveDraw(e, item, index) {
				//赋值选中下标
				this.tabConfig.active = index;
				//获取点击元素的宽度求出元素一半的宽度
				this.createSelectorQuery().select('#m-tab-' + index).boundingClientRect((rect) => {
					this.tabConfig.elWidth = rect.width / 2;
					//获取点击元素距离屏幕左边的距离
					let offsetLeft = e.currentTarget.offsetLeft;
					this.tabConfig.left = offsetLeft + (this.tabConfig.elWidth - this.tabConfig.arrowWidth) / 2;
					// 当前元素 距离屏幕的左边距离 减去 scroll-view的一半 +加元素的一般的宽度 
					this.tabConfig.scrollLeft = offsetLeft - (this.tabConfig.width / 2) + this.tabConfig.elWidth;
					this.$emit('change',index,this.tabConfig);
				}).exec()


			}
		}
	}
</script>

<style scoped>
	#m_tab {
		position: relative;
		width: 100%;

	}

	scroll-view ::-webkit-scrollbar {
		width: 0;
		height: 0;
		color: transparent;
		display: none
	}

	.m_tab_container {
		width: auto;
		white-space: nowrap;
	}

	.m_tab_item {
		display: inline-flex;
		width: 198rpx;
		height: 148rpx;
		align-items: center;
		justify-content: center;
	}
	.circle_item{
		width: 120rpx;
		height: 120rpx;
		border-radius: 120rpx;
		display: inline-flex;
		justify-content: center;
		align-items: center;
		vertical-align: middle;
		transition: background cubic-bezier(0.175, 0.885, 0.32, 1.275) .2s;
		/* background-color: red; */
	}
	.circle_item>.circle_img{
		width: 100rpx;
		height: 100rpx;
		border-radius: 100rpx;
	}
</style>